package com.cn.wx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class Myfilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        这里，就是如果允许，我们就放行，如果不允许，我们就禁止通过

        /**
         * 1.监听器ServletContextListener
         *  监听域对象的生命周期和数据的变化
         *   req.setAttribute("list", list);根据我们值的变化进行监听
         *  2.过滤器，filter
         *      对请求进行拦截，如果符合要求就放行
         *      1）对跨域问题的解决
         *      2）对编码问题的解决
         *      3）对用户登录进行拦截
         *      4）对个别静态文件进行拦截
         *  3.对文件上传会不会？I/O流
         */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url1 = request.getServletPath();
        request.setCharacterEncoding("UTF-8");//对请求设置编码
        servletResponse.setCharacterEncoding("UTF-8");//对响应设置编码
        String url2 = request.getRequestURL().toString();
//        System.out.println(url1 + "-----" + url2);
        if ("/back/login.jsp".equals(url1) || "/login".equals(url1)) {
            filterChain.doFilter(servletRequest, servletResponse);

        } else {

            String sessionUsername = (String) request.getSession().getAttribute("username");
            if (sessionUsername != null) {
                //            可以通过
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                request.getRequestDispatcher("/back/login.jsp").forward(request, servletResponse);
            }

        }
    }


}
